import React, { useEffect, useMemo, useState } from 'react';
import { broadcast } from '@zny/utils';
import { Drawer } from 'antd';

const DynamicApp: React.FC = (props: any) => {
  const {
    mountId,
    type = 'comp',
    pageName,
    compName = 'default',
    props: compProps,
    devPath,
  } = props;
  const [module, setModule] = useState<any>(null);
  const [visible, setVisible] = useState(true);
  const handleHideForm = () => {
    const preventClose = (compProps?.onClose && compProps?.onClose()) === false;
    if (preventClose) {
      return;
    }
    setVisible(false);
  };

  useEffect(() => {
    if (process.env.NODE_ENV === 'development' && devPath) {
      const context = require.context('./', true, /\/form\.tsx?$/);
      const formDict = context.keys().reduce((res: any, key: string) => {
        let match = key.match(/.\/(.*?)\/form.tsx/);
        match && match[1] && (res[match[1].toLocaleLowerCase()] = context(key));
        return res;
      }, {});

      const routeKey = `${devPath
        .split('/')
        .slice(1)
        .join('/')}`.toLocaleLowerCase();
      const formKey = Object.keys(formDict).find(item => item.startsWith(routeKey));
      console.log(
        'Dynamic APP',
        formDict,
        formKey,
        compName,
        formDict[formKey],
        formDict[formKey] && formDict[formKey][compName],
      );
      if (formDict[formKey] && formDict[formKey][compName]) {
        setModule(formDict[formKey]);
        return;
      }
    }
    broadcast('activeWorkflowForm', {
      mountId,
      type,
      pageName,
      compName,
      props: compProps,
    });
  }, [props]);
  useEffect(() => () => broadcast('hideWorkflowForm'), []);
  if (module) {
    const Component = module[compName];
    return (
      <Drawer
        maskClosable={false}
        destroyOnClose
        mask={false}
        visible={visible}
        width={compProps?.width}
        {...compProps?.drawerProps}
        afterVisibleChange={visible => !visible && handleHideForm()}
        onClose={handleHideForm}
      >
        <Component {...compProps} />
      </Drawer>
    );
  }
  return mountId ? <div id={mountId}></div> : null;
};

export const createDynamicApp = (config: any) => {
  return (props: any) => {
    const appProps = useMemo(
      () => ({
        ...config,
        props,
      }),
      [props],
    );
    console.log(appProps, 'appProps');

    return <DynamicApp {...appProps} />;
  };
};

export const WorkflowForm = createDynamicApp({
  type: 'workflowForm',
});

export default DynamicApp;
